<?php

namespace App\Services;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

use Illuminate\Support\Facades\Cache;
use Exception;

class Qiniu
{

    protected $accessKey = '';
    protected $secretKey = '';
    protected $bucketName = '';

    protected $auth = '';

    public function __construct()
    {
        // 用于签名的公钥和私钥
        $this->accessKey = config('filesystems.disks.qiniu.accessKey');
        $this->secretKey = config('filesystems.disks.qiniu.secretKey');
        $this->bucket = config('filesystems.disks.qiniu.bucket');

        // 初始化签权对象
        $this->auth = new Auth($this->accessKey, $this->secretKey);
    }

    /**
     * 获取 token
     *
     * @return string
     */
    public function getToken()
    {
        $tokenCache = Cache::get('qiniu_token_cache');
        if (!$tokenCache) {
            $key = null;
            $expires = 86400;
            // 生成上传Token
            $token = $this->auth->uploadToken($this->bucket, $key, $expires);

            Cache::put('qiniu_token_cache', $token, $expires);

            return $token;
        }

        return $tokenCache;
    }

    /**
     * 上传文件
     */
    public function uploadFile($file)
    {
        $token = $this->getToken();
        // 构建 UploadManager 对象
        $uploadManager = new UploadManager();

        $extStr = explode('.', $file['name']);
        // 重命名
        $name = uniqid() . '.' . $extStr[count($extStr) - 1];
        $filePath = $file['tmp_name'];
        $type = $file['type'];

        list($ret, $err) = $uploadManager->putFile($token, $name, $filePath, null, $type, false);
        if ($err) {
            // 上传失败
            return ['code' => '0', 'msg' => $err, 'key' => ''];
        } else {
            // 成功
            return ['code' => '1', 'msg' => '上传成功', 'key' => $ret['key']];
        }
    }
}
